package com.huayue.dao;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.huayue.entity.AuthCode;
import com.huayue.util.AuthCodeDB;

/**
 * 发送短信验证码
 * 
 */
public class AuthCodeDao {
    /**
     * 向指定手机号发送验证码
     * 
     * @param authCode
     * @return
     */
    public boolean sendAuthCode(AuthCode authCode) {
        DefaultProfile profile =
            DefaultProfile.getProfile("cn-hangzhou", "LTAI4FdDACLC6BKU8qV35qeU", "kT5yJZvbOHpxwb5y1vhM7GZV5LmMrN");
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", authCode.getPhone());
        request.putQueryParameter("SignName", "华悦");
        request.putQueryParameter("TemplateCode", "SMS_180049815");
        // 验证码
        String code = "";
        for (int i = 0; i < 6; i++) {
            code = code + (int)(Math.random() * 9);
        }
        // long code = Math.round((Math.random() + 1) * 1000);
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            // System.out.println(response.getData());
            AuthCodeDB.AUTHCODEDB.put(authCode.getPhone(), code);
            String str = response.getData().substring(12, 14);
            if ("OK".equals(str)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 验证手机号和验证码是否匹配
     * 
     * @param authCode
     * @return
     */
    public boolean verifyAuthCode(AuthCode authCode) {
        // 到验证码库中验证验证码是否正确
        if (AuthCodeDB.AUTHCODEDB.get(authCode.getPhone()) != null) {
            if (AuthCodeDB.AUTHCODEDB.get(authCode.getPhone()).equals(authCode.getAuthCode())) {
                // 验证成功从验证码库中清除该验证码
                AuthCodeDB.AUTHCODEDB.remove(authCode.getPhone());
                return true;
            }
        }
        return false;
    }
}
